//
//  ChangePhoneViewController.m
//  CommunityApp
//
//  Created by 秦乾龙 on 16/12/15.
//  Copyright © 2016年 秦乾龙. All rights reserved.
//

#import "ChangePhoneViewController.h"
#import "NextChangePhoneViewController.h"
#import "AFNetworking.h"//主要用于网络请求方法
#import "UIKit+AFNetworking.h"//里面有异步加载图片的方法
#import "AFHTTPSessionManager.h"
#import "UIButton+WebCache.h"
#import "UIImageView+WebCache.h"
#import "NavView.h"
#import "ZYButton.h"

#define kScreenW [UIScreen mainScreen].bounds.size.width
#define kScreenH [UIScreen mainScreen].bounds.size.height
#define kScale   ([UIScreen mainScreen].bounds.size.width)/750
@interface ChangePhoneViewController ()<UITextFieldDelegate>
@property (nonatomic,strong) NSArray *dataAray;
//@property (nonatomic,strong) TagView *tagView;
@property (nonatomic,strong) NSArray *selectedArray;
@property (nonatomic,strong) UITextField *codeField;
@property (nonatomic,strong) UITextField *phoneField;
@property (nonatomic,retain) UITextField *newphoneField;
@property (nonatomic,strong) NSString *codeStr;
@property (nonatomic,retain) UIButton *codeBtn;
@end

@implementation ChangePhoneViewController

- (void)viewDidLoad {
    [super viewDidLoad];

}

- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self setUI];
}
- (void) setUI
{
    self.navigationItem.titleView = [ViewFactory makeNavigationTitle:@"修改手机号"];
    
    UIBarButtonItem *backBtn = [ViewFactory makeNavigationBackWhite:self action:@selector(backClick)];
    self.navigationItem.leftBarButtonItem = backBtn;
    
    UIButton *buttonNotice = [UIButton buttonWithType:UIButtonTypeCustom];
    buttonNotice.frame = CGRectMake(0, 0, 40, 20);
    buttonNotice.titleLabel.font = [UIFont systemFontOfSize:15];
    [buttonNotice setTitle:@"确定" forState:UIControlStateNormal];
    
    UIBarButtonItem *btnNoticeItem = [[UIBarButtonItem alloc]initWithCustomView:buttonNotice];
    [buttonNotice addTarget:self action:@selector(changeClick) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = btnNoticeItem;

    UIView *backgroundView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH)];
    backgroundView.backgroundColor = [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1.0f];
    [self.view addSubview:backgroundView];
    UIView *phoneView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, 100*kScale)];
    phoneView.backgroundColor = [UIColor whiteColor];
    [backgroundView addSubview:phoneView];
    UILabel *titleLable = [[UILabel alloc]init];
    
    titleLable.text = @"当前绑定手机号:";
    titleLable.font = [UIFont systemFontOfSize:15];
    CGSize titleLableSize = [titleLable sizeThatFits:CGSizeMake(MAXFLOAT, 100*kScale)];
    titleLable.frame = CGRectMake(30*kScale, 0, titleLableSize.width, 100*kScale);

    [phoneView addSubview:titleLable];
    _phoneField = [[UITextField alloc]init];
    _phoneField.delegate = self;
    _phoneField.tag = 10;
    _phoneField.font = [UIFont systemFontOfSize:15];
//    _phoneField.placeholder = @"请输入新手机号码";
    _phoneField.frame = CGRectMake(30*kScale*2+titleLableSize.width,0,ScreenW-30*kScale*3-titleLableSize.width, 100*kScale);
    _phoneField.keyboardType = UIKeyboardTypePhonePad;
    [phoneView addSubview:_phoneField];
    
    UIView *newPhoneView = [[UIView alloc]initWithFrame:CGRectMake(0, 102*kScale, kScreenW, 100*kScale)];
    newPhoneView.backgroundColor = [UIColor whiteColor];
    [backgroundView addSubview:newPhoneView];
    _newphoneField = [[UITextField alloc]init];
    _newphoneField.delegate = self;
    _newphoneField.font = [UIFont systemFontOfSize:15];
    _newphoneField.placeholder = @"请输入新手机号码";
    _newphoneField.tag = 11;
    _newphoneField.frame = CGRectMake(30*kScale, 0, kScreenW-30*kScale, 100*kScale);
    _newphoneField.keyboardType = UIKeyboardTypePhonePad;
    [newPhoneView addSubview:_newphoneField];
    
    
    UIView *codeView = [[UIView alloc]initWithFrame:CGRectMake(0, 102*kScale*2, kScreenW, 100*kScale)];
    codeView.backgroundColor = [UIColor whiteColor];
    [backgroundView addSubview:codeView];
    CGFloat codeBtnW = 100;
    _codeField = [[UITextField alloc]init];
    _codeField.delegate = self;
    _codeField.tag = 12;
    _codeField.font = [UIFont systemFontOfSize:15];
    _codeField.frame = CGRectMake(30*kScale, 0, kScreenW-30*kScale*2-codeBtnW, 100*kScale);
    _codeField.placeholder = @"请输入验证码";
    _codeField.keyboardType = UIKeyboardTypePhonePad;
    [codeView addSubview:_codeField];
    
    _codeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _codeBtn.frame = CGRectMake(kScreenW-codeBtnW, 0, codeBtnW, 100*kScale);
    //    codeBtn setTitle:@"获取验证码" forState:ui
    [_codeBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    _codeBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [_codeBtn setTitle:@"发送验证码" forState:UIControlStateNormal];
    [_codeBtn addTarget:self action:@selector(getCode) forControlEvents:UIControlEventTouchUpInside];
    [codeView addSubview:_codeBtn];
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(kScreenW-codeBtnW-20*kScale, 10*kScale, 6*kScale, 80*kScale)];
    lineView.backgroundColor = [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1.0f];
    [codeView addSubview:lineView];
}
//获取验证码
- (void)request
{
    if (![[_phoneField.text stringByReplacingOccurrencesOfString:@" " withString:@""] isEqualToString:[UserData userphone]])
    {
        [ViewFactory showInfoMsg:@"当前绑定手机号不正确"];
        return;
    }
    if (_newphoneField.text.length==0) {
        [ViewFactory showInfoMsg:@"请输入新手机号"];
        return;
    }
    NSString *urlStr = [NSString stringWithFormat:@"%@/sys/login/memberRegistr/sms/randomCode?mobile_no=%@",APIYIGOU,[_newphoneField.text stringByReplacingOccurrencesOfString:@" " withString:@""]];
    DYBaseRequest *request = [DYBaseRequest new];
    request.requestUrl = urlStr;
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *allDic = [NSDictionary changeType:request.responseJSONObject];
        
        NSLog(@"77777%@",allDic);
        [ViewFactory showSuccess:@"已发送"];
        _codeStr = allDic[@"data"];
        [self timeRun];
        //测试
        //_codeField.text = allDic[@"data"];
        
    } error:^(YTKBaseRequest *request) {
        [ViewFactory showInfoMsg:@"验证码发送失败"];
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
    }];
}

//倒计时
- (void)timeRun
{
    __block NSInteger time = 29; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        
        if(time <= 0){ //倒计时结束，关闭
            
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮的样式
                [_codeBtn setTitle:@"重新发送" forState:UIControlStateNormal];
                //                [_getCodeBtn setTitleColor:[UIColor colorWithRed:210/255.0 green:210/255.0 blue:210/255.0 alpha:1.0f] forState:UIControlStateNormal];
                [_codeBtn setTitleColor:[UIColor colorWithRed:171/255.0 green:147/255.0 blue:103/255.0 alpha:1.0f] forState:UIControlStateNormal];
                _codeBtn.userInteractionEnabled = YES;
            });
            
        }else{
            
            int seconds = time % 60;
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮显示读秒效果
                [_codeBtn setTitle:[NSString stringWithFormat:@"重新发送(%.2d)", seconds] forState:UIControlStateNormal];
                [_codeBtn setTitleColor:[UIColor colorWithRed:171/255.0 green:147/255.0 blue:103/255.0 alpha:1.0f] forState:UIControlStateNormal];
                _codeBtn.userInteractionEnabled = NO;
            });
            time--;
        }
    });
    dispatch_resume(_timer);
}

- (void)backClick
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)changeClick
{
    
    if ([[_phoneField.text stringByReplacingOccurrencesOfString:@" " withString:@""] isEqualToString:[UserData userphone]]) {
        if ([_codeField.text isEqualToString: _codeStr])
        {
            NSString *urlStr = [NSString stringWithFormat:@"%@/userCenter/modifyMemberMobile?user_mobile_no=%@&reg_num=%@",APIYIGOU,[_newphoneField.text stringByReplacingOccurrencesOfString:@" " withString:@""],_codeField.text];
            DYBaseRequest *request = [DYBaseRequest new];
            request.requestUrl = urlStr;
            [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
                NSDictionary *allDic = [NSDictionary changeType:request.responseJSONObject];
                NSLog(@"allDic===%@",allDic);
                
                [ViewFactory showSuccess:@"修改成功"];
                [UserData setUserphone:[_newphoneField.text stringByReplacingOccurrencesOfString:@" " withString:@""]];
            } error:^(YTKBaseRequest *request) {
                NSDictionary *allDic = [NSDictionary changeType:request.responseJSONObject];
                [ViewFactory showInfoMsg:allDic[@"message"]];
            } failure:^(YTKBaseRequest *request) {
                [ViewFactory showErrorStrMsg:NETWORK_ERR];
            }];
            
        }
        else
        {
            [ViewFactory showInfoMsg:@"请输入正确验证码"];
        }

    }
    else
    {
        [ViewFactory showInfoMsg:@"当前绑定手机号不正确"];
    }
}
- (void)getCode
{
    [self request];
}
//键盘
- (void) touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [_phoneField  resignFirstResponder];
    [_codeField resignFirstResponder];
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSLog(@"%@",NSStringFromRange(range));
    if (textField.tag==10||textField.tag==11)
    {
        if (textField) {
            NSString* text = textField.text;
            //删除
            if([string isEqualToString:@""]){
                
                //删除一位
                if(range.length == 1){
                    //最后一位,遇到空格则多删除一次
                    if (range.location == text.length-1 ) {
                        if ([text characterAtIndex:text.length-1] == ' ') {
                            [textField deleteBackward];
                        }
                        return YES;
                    }
                    //从中间删除
                    else{
                        NSInteger offset = range.location;
                        
                        if (range.location < text.length && [text characterAtIndex:range.location] == ' ' && [textField.selectedTextRange isEmpty]) {
                            [textField deleteBackward];
                            offset --;
                        }
                        [textField deleteBackward];
                        textField.text = [self parseString:textField.text];
                        UITextPosition *newPos = [textField positionFromPosition:textField.beginningOfDocument offset:offset];
                        textField.selectedTextRange = [textField textRangeFromPosition:newPos toPosition:newPos];
                        return NO;
                    }
                }
                else if (range.length > 1) {
                    BOOL isLast = NO;
                    //如果是从最后一位开始
                    if(range.location + range.length == textField.text.length ){
                        isLast = YES;
                    }
                    [textField deleteBackward];
                    textField.text = [self parseString:textField.text];
                    
                    NSInteger offset = range.location;
                    if (range.location == 3 || range.location  == 8) {
                        offset ++;
                    }
                    if (isLast) {
                        //光标直接在最后一位了
                    }else{
                        UITextPosition *newPos = [textField positionFromPosition:textField.beginningOfDocument offset:offset];
                        textField.selectedTextRange = [textField textRangeFromPosition:newPos toPosition:newPos];
                    }
                    
                    return NO;
                }
                
                else{
                    return YES;
                }
            }
            
            else if(string.length >0){
                
                //限制输入字符个数
                if (([self noneSpaseString:textField.text].length + string.length - range.length > 11) ) {
                    return NO;
                }
                //判断是否是纯数字(千杀的搜狗，百度输入法，数字键盘居然可以输入其他字符)
                //            if(![string isNum]){
                //                return NO;
                //            }
                [textField insertText:string];
                textField.text = [self parseString:textField.text];
                
                NSInteger offset = range.location + string.length;
                if (range.location == 3 || range.location  == 8) {
                    offset ++;
                }
                UITextPosition *newPos = [textField positionFromPosition:textField.beginningOfDocument offset:offset];
                textField.selectedTextRange = [textField textRangeFromPosition:newPos toPosition:newPos];
                return NO;
            }else{
                return YES;
            }
            
        }
    }
    
    
    return YES;
    
}
-(NSString*)noneSpaseString:(NSString*)string
{
    return [string stringByReplacingOccurrencesOfString:@" " withString:@""];
}

- (NSString*)parseString:(NSString*)string
{
    if (!string) {
        return nil;
    }
    NSMutableString* mStr = [NSMutableString stringWithString:[string stringByReplacingOccurrencesOfString:@" " withString:@""]];
    if (mStr.length >3) {
        [mStr insertString:@" " atIndex:3];
    }if (mStr.length > 8) {
        [mStr insertString:@" " atIndex:8];
        
    }
    
    return  mStr;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
